<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '梦瑶诗歌',
    navigationStyle: 'default',
  },
  needLogin: 'true',
}
</route>
<template>
  <wd-toast />

  <!-- 视频播放器弹窗 -->
  <video-player-popup
    v-model:showVideoPlayer="showVideoPlayer"
    :item="playingItem"
    :loading-prev="loadingPrev"
    :loading-next="loadingNext"
    @end="handleVideoEnded"
    @show-playlist="handleShowPlaylist"
    @prev="playPrevMedia"
    @next="playNextMedia"
  />

  <!-- 播放列表弹窗 -->
  <play-list-popup
    v-model:showPlaylist="showPlaylist"
    :data="playlistData"
    :tabs="playlistTabs"
    :current-page="currentTabPage"
    :playing-item="playingItem"
    :loading="playlistLoading"
    :format-duration="formatTime"
    @play="playFromList"
    @switch-page="switchTabPage"
    @update:show="(val) => (showPlaylist = val)"
  />

  <view class="container">
    <!-- 添加遮罩层，当音频播放器显示时覆盖整个列表区域 -->
    <view
      v-if="playingItem && playingItem.mediaType === 'audio'"
      class="mask-layer"
      @touchmove.prevent
    ></view>

    <!-- 空状态提示 -->
    <view v-if="!loading && mediaList.length === 0" class="empty-state">
      <wd-img
        src=""
        width="300rpx"
        height="300rpx"
        mode="aspectFit"
      />
      <text class="empty-text">哎呀，这里空空的~</text>
      <text class="empty-subtext">小宝贝，这个专辑还没有内容哦</text>
      <text class="empty-suggestion">我们一起去探索其他精彩内容吧！</text>
      <view class="discover-btn">
        <wd-button type="warning" size="medium" @click="goDiscover">
          <wd-icon name="view" color="#fff" />
          去探索
        </wd-button>
      </view>
    </view>

    <view class="search-container" v-show="!showVideoPlayer">
      <wd-search
        v-model="searchKeyword"
        placeholder="根据名称搜索媒体文件"
        @search="handleSearch"
        @clear="handleClear"
        shape="round"
        show-cancel
        clear-trigger="always"
      />
    </view>
    <u-scroll-view
      scroll-y
      class="list-container"
      :class="{ disabled: playingItem && playingItem.mediaType === 'audio' }"
    >
      <view
        v-for="(item, index) in mediaList"
        :key="index"
        class="list-item"
        :style="{ '--index': index }"
      >
        <text class="type-name">{{ item.title }}</text>

        <view class="media-controls">
          <!-- 音频播放控制 -->
          <template v-if="item.mediaType === 'audio'">
            <wd-icon
              :name="playingItem?.id === item.id && isPlaying ? 'pause' : 'play'"
              size="24px"
              @click="handleMediaPlay(item)"
            />
          </template>

          <!-- 视频播放控制 -->
          <template v-else>
            <wd-icon name="play" size="24px" @click="handleMediaPlay(item)" />
          </template>

          <text class="duration">{{ formatTime(item.duration) }}</text>
        </view>
      </view>
    </u-scroll-view>
  </view>

  <!-- 固定底部的音频播放器 -->
  <audio-player-bar
    :show="playingItem && playingItem.mediaType === 'audio'"
    :playing-item="playingItem"
    :is-playing="isPlaying"
    v-model:sliderValue="sliderValue"
    :format-time="formatTime"
    @prev="playPrevMedia"
    @next="playNextMedia"
    @toggle="toggleAudio(playingItem)"
    @stop="stopAudio"
    @seek="handleAudioSeekChange"
  />

  <!-- 分页控件 -->
  <view class="pagination-container" v-show="!showVideoPlayer">
    <wd-pagination
      v-model="currentPage"
      :page-size="pageSize"
      :total="total"
      @change="handlePageChange"
      show-icon
    />
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { http } from '@/utils/http'
import type { MediaView } from '@/api/children.typing'
import { PageResult } from '@/api/poem.typings'
import { useAuthHeaders } from '@/utils/token'
import { useToast } from 'wot-design-uni'
import videoPlayerPopup from '@/components/video-player-popup/video-player-popup.vue'
import playListPopup from '@/components/play-list-popup/play-list-popup.vue'
import audioPlayerBar from '@/components/audio-player-bar/audio-player-bar.vue'
import { useMediaPlayer } from '@/utils/media/useMediaPlayer'

const {
  playingItem,
  isPlaying,
  sliderValue,
  showVideoPlayer,
  toggleAudio,
  stopAudio,
  handleMediaPlay,
  closeVideoPlayer,
  formatTime,
  checkMediaExpiration,
  handleAudioSeekChange,
  audioPlayer,
  videoPlayer,
  calculateTabForCurrentItem,
  playFromList,
  playlistLoading,
  loadingNext,
  loadingPrev,
  playlistTabs,
  currentTabPage,
  showPlaylist,
  lastPlaylistTab,
  ITEMS_PER_TAB,
  playlistData,
  playNextMedia: _playNextMedia,
  playPrevMedia: _playPrevMedia,
} = useMediaPlayer()

// 设置下一曲回调
audioPlayer.setNextTrackCallback(() => {
  console.log('播放结束，自动播放下一曲')
  playNextMedia()
})

const albumId = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const mediaList = ref<MediaView[]>([])
const loading = ref(false)
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL
const toast = useToast()

// 视频播放器相关状态
const isLandscape = ref(false)

// 过期检测定时器
let expirationChecker = null

// 搜索框
const searchKeyword = ref('')

onMounted(() => {
  getMediaList()
  // 启动过期检测
  expirationChecker = setInterval(checkMediaIsExpiration, 60000)
})

onUnmounted(() => {
  if (expirationChecker) {
    clearInterval(expirationChecker)
  }
})

// 页面初次加载
onLoad((options: any) => {
  albumId.value = options.albumId
})

// 计算当前标签页可见的播放列表项
watch([currentTabPage, searchKeyword], () => {
  fetchPlaylistData()
})

// 搜索处理函数
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  getMediaList()
}

// 清除搜索
const handleClear = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  getMediaList()
}

// 切换标签页
const switchTabPage = (index: number) => {
  currentTabPage.value = index
  lastPlaylistTab.value = index
  fetchPlaylistData()
}

// 打开播放列表弹窗
const handleShowPlaylist = async () => {
  showPlaylist.value = true
  // 如果已经有播放项，自动跳转到对应的标签页
  if (playingItem.value) {
    currentTabPage.value = calculateTabForCurrentItem()
  } else {
    // 使用上次访问的标签页
    currentTabPage.value = lastPlaylistTab.value
  }
  await fetchPlaylistData()
}

const getMediaListByParam = async (
  _pageNum: number,
  _pageSize: number,
  _albumId: number,
  _title: string,
) => {
  const requestParams = {
    pageNum: _pageNum,
    pageSize: _pageSize,
    albumId: _albumId,
    title: _title,
  }
  const res = await http.get<PageResult<MediaView>>(
    `${API_BASE_URL}/api/v1/media/page`,
    requestParams,
    useAuthHeaders(),
  )

  if (res.code === 200) {
    // 检查是否有已过期项
    const hasExpired = res.data.list.some(
      (item) => item.expirationDate && Date.now() > item.expirationDate,
    )

    if (hasExpired) {
      toast.warning('部分内容已过期，请刷新页面获取最新内容')
    }
    return res.data
  } else {
    throw new Error(res.msg)
  }
}

const getMediaList = async () => {
  if (loading.value) return
  try {
    const res = await getMediaListByParam(
      currentPage.value,
      pageSize.value,
      albumId.value,
      searchKeyword.value,
    )
    mediaList.value = res.list
    total.value = res.total
  } catch (error) {
    toast.error(`加载列表出错：${error}`)
  } finally {
    loading.value = false
  }
}

const fetchPlaylistData = async () => {
  if (playlistLoading.value) return
  playlistLoading.value = true
  try {
    const res = await getMediaListByParam(
      currentTabPage.value + 1,
      ITEMS_PER_TAB,
      albumId.value, // 假设有专辑ID
      searchKeyword.value,
    )

    playlistData.value = {
      list: res.list || [],
      total: res.total || 0,
      pageNum: res.pageNum,
    }
  } catch (error) {
    toast.error(`获取播放列表失败: ${error.message}`)
    playlistData.value = {
      list: [],
      total: 0,
      pageNum: 1,
    }
  } finally {
    playlistLoading.value = false
  }
}

const goDiscover = () => {
  uni.navigateBack()
}

// 检查媒体过期情况
const checkMediaIsExpiration = () => {
  // 检查播放中的音频项目
  if (playingItem.value && checkMediaExpiration(playingItem.value)) {
    toast.warning('当前播放内容已过期，请刷新页面')
    stopAudio()
  }

  // 检查视频播放中的项目
  if (playingItem.value && checkMediaExpiration(playingItem.value)) {
    toast.warning('当前播放内容已过期，请刷新页面')
    closeVideoPlayer()
  }
}

const handlePageChange = (page: any) => {
  // 切换页面时停止所有播放
  stopAudio()
  closeVideoPlayer()
  currentPage.value = page.value
  getMediaList()
}

const handleVideoEnded = () => {
  if (playingItem.value) {
    videoPlayer.savePlaybackProgress(playingItem.value.id, videoPlayer.duration.value)
  }
  toast.show({ msg: '播放结束，自动播放下一首', duration: 1000 })
  playNextMedia()
}
const handleVideoPause = () => {
  videoPlayer.pause()
  if (playingItem.value) {
    videoPlayer.savePlaybackProgress(playingItem.value.id, videoPlayer.currentTime.value)
  }
}

// 处理时间更新
const handleTimeUpdate = (e: any) => {
  videoPlayer.handleTimeUpdate(e.detail.currentTime)
}

// 处理视频元数据加载
const handleLoadedMetadata = (e: any) => {
  videoPlayer.handleLoadedMetadata(e.detail.duration)
}

// 处理全屏状态变化
const handleFullscreenChange = (e: any) => {
  isLandscape.value = e.detail.direction === 90 || e.detail.direction === -90
}

const playNextMedia = () => {
  _playNextMedia(mediaList.value)
}

const playPrevMedia = () => {
  _playPrevMedia(mediaList.value)
}
</script>

<style scoped lang="scss">
.container {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx;
  padding-bottom: 180rpx;
  min-height: 100vh;
}

/* 遮罩层样式 */
.mask-layer {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 100rpx; /* 确保播放器区域不被覆盖 */
  z-index: 90;
  background: rgba(0, 0, 0, 0.01); /* 几乎透明的背景 */
  pointer-eve: auto;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80vh;
  text-align: center;

  .empty-text {
    font-size: 36rpx;
    font-weight: 600;
    color: #ff6b9c;
    margin-top: 20rpx;
  }

  .empty-text::after {
    content: '✨';
    position: absolute;
    top: -20rpx;
    right: -40rpx;
    font-size: 28rpx;
  }

  .empty-subtext {
    font-size: 28rpx;
    color: #5b8eff;
    margin-top: 12rpx;
  }

  .empty-suggestion {
    font-size: 30rpx;
    color: #ff9d00;
    background-color: #fff9e6;
    padding: 12rpx 24rpx;
    border-radius: 50rpx;
    margin-top: 20rpx;
  }

  .discover-btn {
    display: flex;
    margin-top: 20rpx;
  }
}

.search-container {
  background: #5b8eff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.list-container {
  height: calc(100vh - 200rpx); /* 调整高度 */
  .disabled {
    position: relative;
    z-index: 80; /* 确保在遮罩层下方 */

    .list-item {
      opacity: 0.7; /* 降低透明度 */
      filter: grayscale(50%); /* 添加灰度滤镜 */
      pointer-events: none; /* 禁用点击事件 */
    }
  }
}

.list-item {
  padding: 32rpx 40rpx;
  margin: 20rpx 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(246, 248, 250, 0.9) 100%);
  border-radius: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  transition: all 0.3s ease;
  box-shadow: 0 8rpx 24rpx rgba(143, 157, 184, 0.12);
}

.type-name {
  font-size: 34rpx;
  color: #2c3e50;
  font-weight: 500;
  position: relative;
  padding-left: 40rpx;
  flex: 1;
}

.type-name::before {
  content: '•';
  position: absolute;
  left: 0;
  color: #5b8eff;
  font-size: 48rpx;
  line-height: 1;
  top: -4rpx;
}

.media-controls {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-left: 20rpx;
}

.duration {
  font-size: 28rpx;
  color: #666;
}

/* 分页控件样式 */
.pagination-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
}

/* 动画和其他样式保持不变 */
@keyframes itemEntrance {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.list-item {
  animation: itemEntrance 0.4s ease forwards;
  animation-delay: calc(var(--index) * 0.08s);
  opacity: 0;
}

::-webkit-scrollbar {
  width: 0;
  background: transparent;
}
</style>
